package com.example.demo.file.impl;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.example.demo.entity.FileUpReturnEntity;
import com.example.demo.file.FileManager;
import com.example.demo.util.CommonUtil;
import com.example.demo.util.FileUtils;
import com.example.demo.util.PrimaryKeyUtil;
import com.example.demo.util.PropertiesUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class OssFileManager implements FileManager{
	private final String SAVETYPE = "2";
	
	@Override
	public FileUpReturnEntity uploadSingleFile(MultipartFile file, String module, boolean dontChangeName,
			boolean dontCreateDateDir) throws Exception {
		
		String endpoint = PropertiesUtil.getProperty("oss.endpoint");
		String accessKeyId = PropertiesUtil.getProperty("oss.accessKeyId");
		String accessKeySecret = PropertiesUtil.getProperty("oss.accessKeySecret");
		String bucketName = PropertiesUtil.getProperty("oss.bucketName");
		
		String ossKey = module.endsWith("/")?module:(module+"/");
		
		String fileName = PrimaryKeyUtil.getUUIDWithOutLink() + FileUtils.getFileFormat(file.getOriginalFilename());
		
		if(!dontCreateDateDir) {
			ossKey += new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
		}
		
		if(dontChangeName) {
			fileName = file.getOriginalFilename();
		}
		
		ossKey += fileName;
		
		log.info("oss的key为>>>{}",ossKey);
		
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		
		ossClient.putObject(bucketName, ossKey, file.getInputStream());
		
		ossClient.shutdown();
		
		log.info("文件上传至oss完成");
		
		return new FileUpReturnEntity(ossKey, SAVETYPE);
	}

	@Override
	public List<FileUpReturnEntity> uploadMultiFile(MultipartFile[] files, String module, boolean dontChangeName,
			boolean dontCreateDateDir) throws Exception {
		
		String endpoint = PropertiesUtil.getProperty("oss.endpoint");
		String accessKeyId = PropertiesUtil.getProperty("oss.accessKeyId");
		String accessKeySecret = PropertiesUtil.getProperty("oss.accessKeySecret");
		String bucketName = PropertiesUtil.getProperty("oss.bucketName");
		
		String ossKey = module.endsWith("/")?module:(module+"/");
		
		if(!dontCreateDateDir) {
			ossKey += new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
		}
		
		List<FileUpReturnEntity> ossFileList = new ArrayList<>();
		
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		
		int fileNum = files.length;
		
		for (int i = 0; i < fileNum; i++) {
			MultipartFile file = files[i];
			
			String fileName = PrimaryKeyUtil.getUUIDWithOutLink() + FileUtils.getFileFormat(file.getOriginalFilename());
			
			if(dontChangeName) {
				fileName = file.getOriginalFilename();
			}
			
			String fileOssKey = ossKey + fileName;
			
			ossClient.putObject(bucketName, fileOssKey, file.getInputStream());
			
			log.info("oss的key为>>>{}",fileOssKey);
			
			ossFileList.add(new FileUpReturnEntity(fileOssKey, SAVETYPE));
		}
		
		ossClient.shutdown();
		
		log.info("上传多文件至OSS完成");
		
		return ossFileList;
	}

	@Override
	public void readFileFromRequest(HttpServletResponse response, String fileUrl) throws Exception {
		// TODO Auto-generated method stub
		log.info("(oss)文件的访问路径>>>{}",fileUrl);
		
		fileUrl = CommonUtil.encodeUrlCN(fileUrl);
		
		String endpoint = PropertiesUtil.getProperty("oss.endpoint");
		String accessKeyId = PropertiesUtil.getProperty("oss.accessKeyId");
		String accessKeySecret = PropertiesUtil.getProperty("oss.accessKeySecret");
		String bucketName = PropertiesUtil.getProperty("oss.bucketName");
		
		ClientBuilderConfiguration config = new ClientBuilderConfiguration();
		config.setConnectionTimeout(3000);
		
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, config);
		
		OSSObject object = ossClient.getObject(bucketName, fileUrl);
		
		InputStream ossStream = object.getObjectContent();
		
		ServletOutputStream sos = response.getOutputStream();
		
		IOUtils.copy(ossStream, sos);
		
		 log.info("(oss){}文件访问成功,已输出至响应中去",fileUrl);
		
		IOUtils.closeQuietly(sos);
        IOUtils.closeQuietly(ossStream);
        ossClient.shutdown();
        
        log.info("(oss)关闭连接");
	}

}
